package com.zzyl.nursing.service.impl;

import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.CheckInConfig;
import com.zzyl.nursing.domain.Contract;
import com.zzyl.nursing.domain.Elder;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInContractDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.domain.CheckIn;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Arrays;
import java.util.Optional;

/**
 * 入住信息Service业务层处理
 *
 * @author laoYe
 * @date 2025-10-21
 */
@Slf4j
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    @Autowired
    private ContractMapper contractMapper;

    /**
     * 查询入住信息
     *
     * @param id 入住信息主键
     * @return 入住信息
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住信息列表
     *
     * @param checkIn 入住信息
     * @return 入住信息
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住信息
     *
     * @param checkIn 入住信息
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住信息
     *
     * @param checkIn 入住信息
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住信息
     *
     * @param ids 需要删除的入住信息主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息信息
     *
     * @param id 入住信息主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 申请入住
     *
     * @param checkInApplyDto  入住申请数据传输对象（包含老人、床位、合同等信息）
     */
    @Override
    public void apply(CheckInApplyDto checkInApplyDto) {
        log.info("开始处理入住申请", checkInApplyDto);
        // 1、保存老人信息
        // 1.1、判断老人信息是否已存在(通过身份证号)
        Elder elder = elderMapper.selectOne(new LambdaQueryWrapper<Elder>()
                .eq(Elder::getIdCardNo, checkInApplyDto.getCheckInElderDto().getIdCardNo()));
        // 1.2、判断结果(2-4表示已入住)
        if (elder != null){
            if (elder.getStatus() >= 2 && elder.getStatus() <= 4){
                throw new ServiceException("该老人已经入住");
            }
        }
        //这里是老人未入住的代码,或者没有找到匹配信息
        //2.处理床位状态（更新为占用，利用数据库行锁实现并发控制）
        //2.1 调用Mapper方法更新床位状态，返回受影响的行数
        //int rows = bedMapper.updateBedStatus(checkInApplyDto.getCheckInConfigDto());

    }

    @Override
    public CheckInDetailVo detail(Integer id) {
        CheckInDetailVo vo = new CheckInDetailVo();
        //查询入住信息
        CheckIn checkIn = getById(id);
        //老人信息
        Optional.ofNullable(elderMapper.selectById(checkIn.getElderId()))
                .ifPresent(elder -> {
                    CheckInElderVo elderVo = BeanUtil.toBean(elder, CheckInElderVo.class);
                    //设置年龄
                    int age = IdcardUtil.getAgeByIdCard(elder.getIdCardNo());
                    elderVo.setAge(age);
                    vo.setCheckInElderVo(elderVo);
                });
        //将老人信息转成vo
        //家属信息
        String jsonStr = checkIn.getRemark();
        List<ElderFamilyVo> elderFamilyVos = JSONUtil.toList(jsonStr, ElderFamilyVo.class);
        //设置家属信息
        vo.setElderFamilyVoList(elderFamilyVos);
        //入住配置信息
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(new LambdaQueryWrapper<CheckInConfig>().eq(CheckInConfig::getCheckInId, checkIn.getId()));
        CheckInConfigVo checkInConfigVo = BeanUtil.toBean(checkInConfig, CheckInConfigVo.class);
        //转成vo,开始和结束日期
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        vo.setCheckInConfigVo(checkInConfigVo);
        //合同信息
        Contract contract = contractMapper.selectOne(new LambdaQueryWrapper<Contract>().eq(Contract::getElderId, checkIn.getElderId()));
        vo.setContract(contract);
        return vo;
    }
}
